<template>
  <div>
    <el-upload
      ref="upload"
      :action="action"
      :data="dataObj"
      :list-type="listType"
      :file-list="fileList"
      :show-file-list="showFile"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">

      <el-button type="primary" v-show="listType == 'picture'">{{clickText}}</el-button>
      <div slot="tip" class="el-upload__tip" v-show="listType == 'picture'">只能上传单文件<a style="color: #409EFF"
                                                                                      @click="iconClick"></a></div>
      <div class="avatarBox" v-show="listType != 'picture'">
        <img v-if="fileList.length >0" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus"></i>
      </div>
    </el-upload>
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible">
      <img width="100%" :src="fileList.length >0 ? fileList[0].url:''" alt="">
    </el-dialog>
    <icon-dialog ref="iconDialog" @confirm="dialogConfirm"/>
  </div>
</template>
<script>
  import {policy} from '@/api/oss'
  import IconDialog from '@/components/IconDialog'
  import utils from '../../utils/utils'

  export default {
    name: 'singleUpload',
    props: {
      value: String,
      listType: {
        type: String,
        default: 'picture'
      },
      clickText: String // 按钮名称
    },
    watch: {
      value: {
        handler(newVal, oldVal) {
          if (this.value != null && this.value !== '' && this.first) {
            this.first = false;//用变量控制第一次才改变值
            this.fileList = [{name: this.value.substr(this.value.lastIndexOf("/") + 1), url: newVal}]
          }
        },
        immediate: true
      },
      listType: {
        /*handler(newVal, oldVal) {
            if(newVal == 'picture'){
                this.showFile = true
            }else {
                this.showFile = false
            }
        },
        immediate: true*/
      },
    },
    computed: {
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value != null && this.value !== '') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null;
        }
      },
    },
    components: {
      IconDialog
    },
    data() {
      return {
        showFile: false,
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: ''
        },
        action: '',
        dialogVisible: false,
        fileList: [],
        first: true,
        uuid: ''
      };
    },
    methods: {
      iconClick() {
        this.$refs.iconDialog.show()
      },
      dialogConfirm(data) {
        this.fileList = [{name: data.name, url: data.iconUrl}];
        this.emitInput(this.fileList[0].url);
      },
      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput('');
      },
      handlePreview(file) { // 预览
        // this.dialogVisible = true;
      },
      beforeUpload(file) {
        this.$emit('uploadFn', false)
        let _self = this;
        _self.uuid = utils.getUUID()
        console.log('fileList', this.fileList);
        console.log('showFileList', this.showFileList)
        if (!utils.isNull(this.fileList[0].name) && !utils.isNull(this.fileList[0].url)) {
          this.handleRemove()
        }
        // console.log('类型','file/jasper'.indexOf(file.type))
        if ('file/jasper'.indexOf(file.type) == -1) {
          this.showFile = false
          _self.$message({
            message: "请上传.jasper格式的文件",
            offset: 120,
            center: true
          });
          return false;
        } else {
          this.showFile = true
          return new Promise((resolve, reject) => {
            policy().then(response => {
              _self.dataObj.policy = response.data.policy;
              _self.dataObj.signature = response.data.signature;
              _self.dataObj.ossaccessKeyId = response.data.accessKeyId;
              _self.dataObj.dir = response.data.dir;
              _self.dataObj.key = response.data.dir + '/' + _self.uuid + "${filename}";
              _self.dataObj.host = response.data.host;
              _self.action = response.data.action;
              resolve(true)
              this.$emit('uploadFn', true)
            }).catch(err => {
              console.log(err)
              reject(false)
            })
          })
        }

      },
      handleChange(file, fileList) {
        this.fileList = fileList.slice(-1);
      },
      handleUploadSuccess(res, file) {
        this.emitInput(this.dataObj.host + '/' + this.dataObj.dir + '/' + this.uuid + file.name);
      }
    }
  }
</script>
<style scoped>
  .avatarBox {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .avatar {
    width: 99%;
    height: 99%;
    display: block;
  }
</style>
